<?php
namespace App\Admin\Controllers;

use App\Admin\Actions\Call;
use App\Admin\Actions\GiveOther;
use App\Admin\Actions\NeedHelp;
use App\Admin\Extensions\Tools\ExcelImport;
use App\Models\Client;
use App\Models\CrmConfig;
use App\Models\Department;
use App\Models\User;
use Carbon\Carbon;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;

class BaseController extends AdminController
{
    protected $sh_status = [0=>'待审核',1=>'通过',2=>'驳回',3=>'审核中'];

    public function permission()
    {
        $permission = [
            'query',
            'create',
            'import',
            'export',
            'forward',
            'edit',
            'delete',
        ];

        DB::table('admin_menu')->where('parent_id','>',0)->get();
    }

    public function __construct()
    {
        Admin::script("
        $(document.body)
            .append('<'+'script'+` src='/assets/js/records.js'>`+'<'+'/script>');
    ");
    }

    public static function isManager()
    {
        return Admin::user()->isRole('manager');
    }

    public static function isSuper()
    {
        return Admin::user()->isRole('administrator');
    }

    public static function current_id()
    {
        return Admin::user()->id;
    }

    /**
     * @param Grid $grid
     * @param bool $import_enable   是否允许导入
     * @param bool $forward_enable  是否允许转交
     * @param bool $call_enable     是否允许拨号
     * @param bool $secret_enable   是否只查看自己的keh
     * @param bool $need_help   是否可选协助
     * @return Grid
     */
    public static function permissions(
        Grid $grid,
        $import_enable = false,
        $forward_enable = false,
        $call_enable = false,
        $secret_enable = true,
        $need_help = true)
    {

        $uri = str_replace('admin/','',Route::current()->uri);
        // $uri = clue

        // 查询权限
        if(! Admin::user()->can($uri.'.query')){
            $grid->disableFilter();
        }
        // 新增权限
        if(! Admin::user()->can($uri.'.create')){
            $grid->disableCreateButton();
        }
        // 导入权限
        if(Admin::user()->can($uri.'.import') && $import_enable){
            $grid->tools(function ($tools){
                $tools->append("<a class='btn btn-sm btn-info' href='/upload/files/导入格式.xlsx' target='_blank' download='导入格式'>下载数据导入格式</a>");
                $tools->append(new ExcelImport());
            });
        }
        // 导出权限
        if(! Admin::user()->can($uri.'.export')){
            $grid->disableExport();
        }
        // 转交权限
        if(Admin::user()->can($uri.'.forward') && $forward_enable){
            $grid->batchActions(function ($batch){
                $batch->add(new GiveOther());
            });
        }

        if($need_help){
            $grid->batchActions(function ($batch){
                $batch->add(new NeedHelp());
            });
        }

        // 编辑权限
        if(! Admin::user()->can($uri.'.edit')){
            $grid->actions(function ($actions){
                $actions->disableEdit();
            });
        }
        // 删除权限
        if(! Admin::user()->can($uri.'.delete')){
            $grid->actions(function ($actions){
                $actions->disableDelete();
            });
            $grid->batchActions(function ($batch){
                $batch->disableDelete();
            });
        }

        // 允许拨号
        if($call_enable == true){
            $grid->actions(function ($actions){
                $actions->add(new Call($actions->row['id']));
            });
        }

        // 数据保护，只能查看自己的
        if($secret_enable == true){

            // 销售的正常逻辑
            if(Admin::user()->isRole('employee')){
                if(Admin::user()->is_leader == 1){
                    // 获取当前部门下所有人
                    $employee_ids = Department::getEmployees(self::current_id());
                    $grid->model()->whereIn('employee_id',$employee_ids);
                }else{
                    $grid->model()->where('employee_id', self::current_id());
                }
            }else if(Admin::user()->isRole('quanzheng')){
                // 权证人的视角
                $client_ids = \App\Models\NeedHelp::query()
                    ->where('helper_id',Admin::user()->id)
                    ->pluck('id')->toArray();
                $grid->model()->whereIn('id',$client_ids);
            }
        }
        // 默认设置  关闭查看
        $grid->actions(function ($actions){
            $actions->disableView();
        });
        return $grid;
    }

    /**
     * 统一搜索
     * @param Grid\Filter $filter
     */
    public static function filter(Grid\Filter $filter)
    {
        $users = User::Users();
        $filter->disableIdFilter();
        $filter->column(1/3,function (Grid\Filter $filter){
            $filter->like('name', '客户姓名');
            $filter->equal('employee_status', '客户类型')->select(CrmConfig::getKeyValue('follow_status'));
            $filter->equal('quanzheng_status', '权证类型')->select(CrmConfig::getKeyValue('quanzheng_status'));
            $filter->like('mobile', '手机号码');
            $filter->equal('china_id', '身份证号');
            $filter->between('income','打卡工资（¥）');
            $filter->between('family_in','其他收入（¥）');
            $filter->equal('shebao','有无社保')->select([1=>'有',2=>'无']);
            $filter->between('shebao_in','社保个人月缴存额（¥）');
            $filter->equal('gongjijin','有无公积金')->select([1=>'有',2=>'无']);
            $filter->between('gongjijin_in','公积金个人月缴存额（¥）');
            $filter->between('debt','未结清放贷余额（¥）');
            $filter->between('monthly_debt','每月还贷额（¥）');
            $filter->like('baoxian.bx_company','保险公司');
            $filter->like('baoxian.bx_type','保险类型');
            $filter->like('baoxian.bx_tbr','保险投保人');
        });
        $filter->column(1/3,function (Grid\Filter $filter){
            $filter->equal('sex', '性别')->select([1=>'男',2=>'女']);
            $filter->equal('education', '学历')->select(Client::education);
            $filter->equal('had_dk', '有无贷款')->select([1=>'有',2=>'无']);
            $filter->equal('current_prov','当前所在省份');
            $filter->equal('current_city','当前所在城市');
            $filter->equal('current_area','当前所在区');
            $filter->like('current_street','当前居住街道');
            $filter->like('company','单位名称');
            $filter->like('company_address','单位地址');
            $filter->like('company_type','行业类型');
            $filter->equal('company_belong','单位性质')->select(Client::company_type);
            $filter->equal('company_post','公司职位')->select(Client::company_post);
            $filter->between('baoxian.value','保险年缴费用');
            $filter->between('baoxian.buy_time','保险购买日期');
            $filter->between('baoxian.bx_stop','保险是否断缴');
        });
        $filter->column(1/3,function (Grid\Filter $filter){
            $filter->equal('marriage', '婚姻状况')->select(Client::marriage);
            $filter->between('age','年龄');
            $filter->equal('current_prov','籍贯所在省份');
            $filter->equal('current_city','籍贯所在城市');
            $filter->equal('current_area','籍贯所在区');
            $filter->like('current_street','籍贯居住街道');
            $filter->equal('houses.pay_type','房产类型')->select(CrmConfig::getKeyValue('money_pay_type'));
            $filter->equal('houses.own_type','房产状态')->select(CrmConfig::getKeyValue('own_type'));
            $filter->equal('houses.status','房产是否抵押')->select([1 => '是', 2 => '否']);
            $filter->between('houses.house_size','房产面积（m²）')->select([1 => '是', 2 => '否']);
            $filter->between('houses.value','房产价值（万）');
            $filter->between('cars.value','车辆价格（万）');
            $filter->between('cars.buy_time','车辆购入日期');
            $filter->equal('cars.status','车辆是否抵押')->select([1 => '是', 2 => '否']);
            $filter->equal('employee.dep_l3','所属三级部门')->select(Department::getLevel(3));
            $filter->equal('employee.dep_l2','所属二级部门')->select(Department::getLevel(2));
            $filter->equal('employee.dep_l1','所属一级部门')->select(Department::getLevel(1));
        });
    }

    public static function callOut(Grid $grid)
    {
        $grid->column('mobile', '手机号')->modal('呼叫记录',function ($modal) {
            return self::records_table_and_form($modal);
        });
    }

    public static function newestRecords(Grid $grid)
    {
        $grid->column('last_updated_at', '最新跟进时间')
            ->display(function ($model){
                if(isset($this->client->records)){
                    return $this->client->oneLastRecords->created_at;
                }else{
                    return $this->oneLastRecords->created_at;
                }
            })->modal('跟进记录',function ($modal) {
                if(isset($modal->client->records)){
                    $modal = $modal->client;
                }
                return self::records_table_and_form($modal);
            });
    }

    /**
     * 左边是最新跟进记录表格，右边是表单
     * @param $modal
     * @return string
     */
    protected static function records_table_and_form($modal){
        if(! isset($modal->records)){
            return  '';
        }
        $headers = ['创建时间','销售人员','跟进记录','操作计划'];
        $table_rows = [];
        $user = User::Users();
        foreach ($modal->records as $key => $item){
            $table_rows[$key] = [
                $item->created_at,
                $user[$item->employee_id],
                $item->records,
                $item->plan,
            ];
        }
        $table = new Table($headers, $table_rows);

        $form = new Form();
        $form->action('records2');
        $form->hidden('client_id','客户ID')->default($modal->id);
        $form->hidden('employee_id','员工ID')->default(self::current_id());
        $form->textarea('records','跟进记录');
        $form->textarea('plan','跟进计划');
        $form->hidden('created_at','创建时间')->default(Carbon::now()->toDateTimeString());

        $row = new Row();
        $row->column(8,$table->render());
        $row->column(4,$form->render());
        return $row->render();
    }


    public static function closeAll(Grid $gird)
    {
        $gird->disableBatchActions();
        $gird->disableCreateButton();
        $gird->disableRowSelector();
        $gird->disableActions();
        $gird->disableExport();
        $gird->disablePerPageSelector();
        $gird->disableFilter();
        $gird->disableTools();
        $gird->disableColumnSelector();
    }


}
